import configparser
import os
import platform
from device_def import DeviceInfo

from util.util_net import NetUtil
from util.util_system import SystemUtil

class DeviceUtil:

    @staticmethod
    def save_config(device_info : DeviceInfo, config_path : str = "device.ini"):
        """保存设备配置到文件"""
        config = configparser.ConfigParser()
        
        # 设备信息
        config['Device'] = {
            'Name': f'{device_info.name}',
            'Serial': f'{device_info.serial}',
            'Remark': f'{device_info.remark}'
        }
        
        # 网络接口信息
        config['Interface'] = {
            'Name': f'{device_info.interface_name}',
            'IP': f'{device_info.ip}',
            'Submask': f'{device_info.submask}',
            'Gateway': f'{device_info.gateway}'
        }

        config['time_sync'] = {
            "ntp_url": f"{device_info.ntp_url}"
        }
        
        try:
            with open(config_path, 'w', encoding='utf-8') as f:
                config.write(f)
            return True
        except Exception as e:
            return False

    @staticmethod
    def load_config(config_path : str = "device.ini"):
        """从配置文件加载设备信息"""
        if not os.path.exists(config_path):
            device = DeviceUtil.generate_default_device_info()
            if DeviceUtil.save_config(device) == False:
                return None
        try:
            device_info = DeviceInfo()
            config = configparser.ConfigParser()
            config.read(config_path, encoding='utf-8')
            
            # 读取设备信息
            if 'Device' in config:
                device_info.name = config['Device'].get('Name', '')
                device_info.serial = config['Device'].get('Serial', '')
                device_info.remark = config['Device'].get('Remark', '')
            
            # 读取网络接口信息
            if 'Interface' in config:
                device_info.interface_name = config['Interface'].get('Name', '')
                # ret,ip, submask, gateway = NetUtil.get_network_info_ipv4(device_info.interface_name)
                # if ret == False:
                #     return None
                device_info.ip = config['Interface'].get('ip', '')
                device_info.submask = config['Interface'].get('submask', '')
                device_info.gateway = config['Interface'].get('gateway', '')
                # device_info.ip = ip
                # device_info.submask = submask
                # device_info.gateway = gateway

            if "time_sync" in config:
                device_info.ntp_url = config["time_sync"].get("ntp_url", "ntp.tencent.com")

            return device_info
        except Exception as e:
            print(e)
            return None

    @staticmethod
    def generate_default_device_info():
        """生成默认设备信息"""
        device_info = DeviceInfo()
        device_info.name = "Default Device"
        device_info.serial = NetUtil.generate_serial()
        device_info.remark = "Auto-generated device configuration"
        
        device_info.interface_name = NetUtil.get_default_interface()
        ret, ip, submask, gateway = NetUtil.get_network_info_ipv4(device_info.interface_name)
        if ret:
            device_info.ip = ip
            device_info.submask = submask
            device_info.gateway = gateway
        else:
            print("获取网络信息失败")
            device_info.ip = ""
            device_info.submask = "255.255.255.0"
            device_info.gateway = ""
        
        device_info.ntp_url = "ntp.tencent.com"
        return device_info
    
    @staticmethod
    def applyDevice(device : DeviceInfo):
        DeviceUtil.__applyDeviceNtpURL(device)
        return DeviceUtil.__applyDeviceInterface(device)
    
    @staticmethod
    def __applyDeviceInterface(device : DeviceInfo):
        return NetUtil.set_static_ip(device.interface_name, device.ip, device.submask, device.gateway)
        
    @staticmethod
    def __applyDeviceNtpURL(device : DeviceInfo):
        return SystemUtil.sntp_sync_time(device.ntp_url)

if __name__ == '__main__':

    device_info = DeviceUtil.load_config("device.ini")
    if device_info is not None:
        print(device_info)
    else:
        print("加载失败")
        device_info = DeviceUtil.generate_default_device_info()

    DeviceUtil.applyDevice(device_info)

    ret = DeviceUtil.save_config(device_info, "test_save_device.ini")
    if ret:
        print("保存成功")
    else:
        print("保存失败")
